require(['select2', 'date', 'validator', 'grid'], function () {
    var $grid = $('#grid'),editDialog,
        $addHolidayBnt = $("#addHolidayBnt"),
        $holidaySearch = $("#holidaySearch");
    var cssprop = {
        color: "red"
    };
    var cnt = 0, $formData = $('#formData'),
        $holidayListForm = $("#holidayListForm"),
        $setHolidayTab = $("#setHolidayTab");

    $("#qyear").val(new Date().getFullYear());

    $formData.initForm();
    $holidayListForm.initForm();
    //grid初始化
    function gridInit() {
        $grid.grid({
            url: "/holidayParam/searchHolidayPage.htm",
            colModel: [
                {name: "holidayId", label: 'holidayId', key: true, hidden: true},
                {name: "year", label: '年份'},
                {name: "holiday", label: '节日', dict: "HOLI0000"},
                {name: "strDate", label: '日期'},
                {name: "workDayInd", label: '是否工作日'}
            ],
            height: $(window).height() - 53,
            showPaper: true,
            gridComplete: function () {
                var rowIds = $grid.jqGrid('getDataIDs');
                var content = "";
                for (var i = 0; i < rowIds.length; i++) {
                    var rowId = rowIds[i];
                    var rowObject = $grid.jqGrid('getRowData', rowId);
                    if (rowObject.holiday != '非假日') {
                        content = "<span>" + rowObject.holiday + "</span>";
                        $grid.jqGrid("setCell", rowId, "holiday", content, cssprop);
                    }
                    if (rowObject.workDayInd == 0) {
                        content = "<span>非工作日</span>";
                        $grid.jqGrid("setCell", rowId, "workDayInd", content, cssprop);
                    } else {
                        content = "<span>工作日</span>";
                        $grid.jqGrid("setCell", rowId, "workDayInd", content);
                    }
                }
            }
        });
    }



    // 点击设定节假日按钮
    $addHolidayBnt.on("click", function () {
        getEditDialog('设定节假日').dialog('exec', 'reset');
    });

    /**
     * 获取表单对话框，如果没有就先创建
     * @param option {object} 对话框配置
     * @returns {jQuery}
     */
    function getEditDialog(option) {
        option = option || {};
        if (editDialog) {
            editDialog.dialog('open');
            if (option.title) {
                editDialog.dialog('setOption', 'title', option.title);
            }
            //editDialog.dialog('exec', 'clearAll');
        } else {
            editDialog = $('<div>').dialog({
                title: option.title || '设定节假日',
                url: './master/setting/sysHolidayParamSetEdit.htm',
                height: 500,
                width: 700,
                autoOpen: true,
                buttons: [
                    {
                        text: '确定',
                        css: 'mr10',
                        click: function () {
                            var _t = this;
                            $(_t).dialog('exec', 'add',function(){
                                reload(true);
                            });
                        }
                    },
                    {
                        text: '关闭',
                        css: 'btn-cancel',
                        click: function () {
                            $(this).dialog('close');
                        }
                    }
                ]
            });
        }
        return editDialog;
    }

    $setHolidayTab.on("click.addRowA", "#addRowA", function () { // 添加行的点击事件
        cnt++;
        var $endTR = $("#endTR");
        var newTR = "<tr id='newTR'>"
            + "<td style='border-left: 1px solid #DCDCDC' class='ac'><select dict='HOLI0000' name='holidays' class='u-input' style='width:100px'><option value=''>请选择</option></select></td>"
            + "<td class='ac'><div class='select-box select-box-large'><input type='text' id='add_beginDate" + cnt + "' name='beginDates' data-validator='{required:true}' class='u-input' style='width:100px' onclick=\"WdatePicker({isShowClear:true,dateFmt:'yyyy-MM-dd'})\"><span class='icon-date'></span></div></td>"
            + "<td class='ac'><div class='select-box select-box-large'><input type='text' id='add_endDate" + cnt + "' name='endDates' data-validator=\"{dateCompare:'add_beginDate" + cnt + "',required:true}\" class='u-input' style='width:100px' onclick=\"WdatePicker({isShowClear:true,dateFmt:'yyyy-MM-dd'})\"><span class='icon-date'></span></div></td>"
            + "<td class='ac'><select name='workDayInds' class='u-input' style='width:100px;'><option value='0'>非工作日</option><option value='1'>工作日</option></select></td>"
            + "<td class='ac'><a class='operate operate-delete delRowA' href='javascript:;'>删除</a></td>"
            + "</tr>";
        $endTR.after(newTR);
        // 初始化下拉框数据
        // 切换id
        var $newTR = $("#newTR");
        $endTR.removeAttr("id");
        $newTR.attr({id: "endTR"});
        $holidayListForm.initForm();
    }).on("click.delRowA", ".delRowA", function () { // 删除行的点击事件
        if ($("#setHolidayTab tr").length == 3) {
            $.messager.alert("提示", "这是最后一条信息了，请不要删除。", "info");
        } else {
            var delTR = $(this).closest('tr');
            if (delTR.attr("id") === "endTR") {
                delTR.prev().attr({id: "endTR"});
            }
            delTR.remove();
        }
    });


    // 批量重置
    $("#resetHolidayBnt").on("click", function () {
        var strDates = $grid.jqGrid('getGridParam', 'selarrrow');
        if (strDates.length == 0) {
            $.messager.alert("提示", "请勾选重置项，进行批量重置！", "info");
        } else {
            $.messager.confirm("是否重置", "是否批量重置为非节假日、工作日？", function (r) {
                if (r) {
                    var holidayIds = [];
                    var holiday = "";
                    for (var i = 0; i < strDates.length; i++) {
                        holiday = $grid.jqGrid('getRowData', strDates[i]);
                        holidayIds[i] = holiday.holidayId;
                    }
                    $.ajaxExt({
                        url: "/holidayParam/resetHolidays.htm",
                        data: {'holidayIds': holidayIds.toString(), 'strDates': strDates.toString()}
                    }).done(function () {
                        $grid.trigger("reloadGrid");
                        $.messager.alert("提示", "批量重置成功。", "info");
                    });
                }
            });
        }
    });

    //查询grid
    $holidaySearch.click(function () {
        $grid.grid('setGridParam', {
            datatype: "JSON",
            page: 1,
            postData: {
                "qyear": $("#qyear").val(),
                "qholiday": $("#qholiday").val()
            }
        }).trigger("reloadGrid");
    });
    //新增后执行
    function reload(close){
        $grid.grid('setGridParam', {
            datatype: "JSON",
            page: 1,
            postData: {
                "qyear": $("#qyear").val(),
                "qholiday": $("#qholiday").val()
            }
        }).trigger("reloadGrid");
        close && editDialog.dialog('close');
    };

    gridInit();
});